<template>
  <div class="leave-form-page">
    <!-- 固定头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">请假申请</h1>
      </div>
    </div>

    <div class="form-container">

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="84px"
        class="form-body login-like-form"
      >
        <el-form-item label="员工姓名" prop="userName">
          <el-input v-model="formData.userName" disabled placeholder="自动填充当前登录用户" />
        </el-form-item>
        
        <el-form-item label="账户名称" prop="userAccount">
          <el-input v-model="formData.userAccount" disabled placeholder="自动填充当前登录账户" />
        </el-form-item>
        
        <el-form-item label="请假类型" prop="leaveType">
          <el-select v-model="formData.leaveType" placeholder="请选择" :disabled="!canEdit">
            <el-option label="事假" :value="0" />
            <el-option label="病假" :value="1" />
            <el-option label="年假" :value="2" />
            <el-option label="调休" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            :disabled="!canEdit"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            :disabled="!canEdit"
          />
        </el-form-item>

        <el-form-item label="请假天数" prop="days">
          <div class="days-display">
            <span class="days-value">{{ formData.days }}</span>
            <span class="days-unit">天</span>
          </div>
        </el-form-item>

        <el-form-item label="请假原因" prop="reason">
          <el-input
            v-model="formData.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入请假原因"
            maxlength="500"
            show-word-limit
            :disabled="!canEdit"
          />
        </el-form-item>
      </el-form>

    </div>
    
    <!-- 底部按钮 -->
    <div class="bottom-submit">
      <button class="submit-btn primary" :disabled="submitLoading" @click="handleSubmit">
        {{ submitButtonText }}
      </button>
      <button class="submit-btn secondary" @click="goMyLeaves">
        我的请假
      </button>
    </div>
  </div>
  </template>

<script setup>
import { ref, watch, onMounted, onUnmounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addLeave, getLeave, updateLeave } from '@/api/leave/leave'
import { getUserInfo, getUserDetailInfo } from '@/utils/auth'
import { getInfo } from '@/api/login'

const router = useRouter()
const route = useRoute()

const formRef = ref(null)
const submitLoading = ref(false)
const isEditMode = ref(false)
const leaveId = ref(null)
const leaveStatus = ref(2) // 默认为待审批状态
const formData = ref({
  leaveType: 0, // 使用数字类型，0代表事假
  startTime: '',
  endTime: '',
  days: 0,
  reason: '',
  userName: '',
  userAccount: '',
  userId: null
})

// 计算属性：是否为待审核状态（只有待审核才能修改）
const canEdit = computed(() => {
  return !isEditMode.value || leaveStatus.value === 2
})

// 计算属性：按钮文本
const submitButtonText = computed(() => {
  if (isEditMode.value) {
    return canEdit.value ? '确认修改' : '查看详情'
  }
  return '发起请假'
})

const formRules = {
  leaveType: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  reason: [
    { required: true, message: '请输入请假原因', trigger: 'blur' },
    { min: 5, max: 500, message: '请假原因长度在 5 到 500 个字符', trigger: 'blur' }
  ]
}

const calculateDays = (startTime, endTime) => {
  if (!startTime || !endTime) return 0
  try {
    const s = new Date(String(startTime).replace('T', ' ').split('+')[0].split('.')[0])
    const e = new Date(String(endTime).replace('T', ' ').split('+')[0].split('.')[0])
    if (isNaN(s.getTime()) || isNaN(e.getTime())) return 0
    const diff = (e - s) / (1000 * 60 * 60 * 24)
    return diff > 0 ? Number(diff.toFixed(1)) : 0
  } catch {
    return 0
  }
}

watch([() => formData.value.startTime, () => formData.value.endTime], ([s, e]) => {
  formData.value.days = calculateDays(s, e)
})

const handleSubmit = async () => {
  if (!formRef.value) return
  
  // 如果是查看模式（非待审核状态），直接返回
  if (isEditMode.value && !canEdit.value) {
    return
  }
  
  try {
    await formRef.value.validate()
    
    // 验证userId是否存在
    if (!formData.value.userId) {
      ElMessage.error('用户信息获取失败，请刷新页面重试')
      return
    }
    
    if (formData.value.startTime && formData.value.endTime) {
      const s = new Date(formData.value.startTime)
      const e = new Date(formData.value.endTime)
      if (e <= s) {
        ElMessage.warning('结束时间必须大于开始时间')
        return
      }
    }
    submitLoading.value = true
    
    // 构建请求数据
    const payload = {
      leaveTime: formData.value.startTime, // 使用用户选择的开始时间
      backTime: formData.value.endTime, // 使用用户选择的结束时间
      type: formData.value.leaveType,
      reason: formData.value.reason,
      cLeaveUser: {
        userId: formData.value.userId
      }
    }
    
    let res
    if (isEditMode.value) {
      // 编辑模式：更新请假记录
      payload.id = leaveId.value
      res = await updateLeave(payload)
      if (res.code === 200) {
        ElMessage.success('修改成功')
        router.push('/my-leaves')
      } else {
        ElMessage.error(res.msg || '修改失败')
      }
    } else {
      // 新增模式：创建请假记录
      payload.leaveTime = new Date().toISOString().replace('T', ' ').split('.')[0] // 当前时间作为请假时间
      res = await addLeave(payload)
      if (res.code === 200) {
        ElMessage.success('发起成功')
        router.push('/my-leaves')
      } else {
        ElMessage.error(res.msg || '提交失败')
      }
    }
  } finally {
    submitLoading.value = false
  }
}

const goMyLeaves = () => {
  router.push('/my-leaves')
}

// 加载请假数据（编辑模式）
const loadLeaveData = async (id) => {
  try {
    const res = await getLeave(id)
    if (res.code === 200 && res.data) {
      const leave = res.data
      
      // 填充表单数据
      formData.value.leaveType = leave.type || 0
      formData.value.startTime = leave.leaveTime || ''
      formData.value.endTime = leave.backTime || ''
      formData.value.reason = leave.reason || ''
      
      // 设置请假状态
      leaveStatus.value = leave.status !== undefined ? leave.status : 2
      
      // 计算天数
      formData.value.days = calculateDays(formData.value.startTime, formData.value.endTime)
    } else {
      ElMessage.error('获取请假信息失败')
      router.push('/my-leaves')
    }
  } catch (error) {
    console.error('加载请假数据失败:', error)
    ElMessage.error('获取请假信息失败')
    router.push('/my-leaves')
  }
}

// 使当前页面在容器中不滚动，并与底部导航接壤
let pageContentEl = null
onMounted(async () => {
  // 检查路由参数，判断是否为编辑模式
  const { id, status, mode } = route.query
  if (mode === 'edit' && id) {
    isEditMode.value = true
    leaveId.value = parseInt(id)
    leaveStatus.value = parseInt(status) || 2
  }
  
  // 参考Home.vue中的用户信息获取方式
  let userInfoData = null
  
  try {
    // 1. 先尝试从API获取用户详细信息
    const res = await getInfo()
    if (res.code === 200 && res.user) {
      userInfoData = res.user
    }
  } catch (error) {
    // API获取用户信息失败，尝试从本地存储获取
  }
  
  // 2. 如果API获取失败，尝试从本地存储获取
  if (!userInfoData) {
    userInfoData = getUserInfo()
  }
  
  // 3. 如果还是获取不到，尝试从userDetailInfo获取
  if (!userInfoData) {
    const userDetailInfo = getUserDetailInfo()
    if (userDetailInfo && userDetailInfo.user) {
      userInfoData = userDetailInfo.user
    }
  }
  
  // 4. 填充表单数据
  if (userInfoData) {
    // 获取用户名，优先级：nickName > nickname > realName > userName > username
    formData.value.userName = 
      userInfoData.nickName || 
      userInfoData.nickname || 
      userInfoData.realName || 
      userInfoData.userName || 
      userInfoData.username || 
      '未知用户'
      
    // 获取账户名，优先级：userName > username
    formData.value.userAccount = 
      userInfoData.userName || 
      userInfoData.username || 
      '未知账户'
      
    // 获取用户ID
    formData.value.userId = userInfoData.userId
  } else {
    ElMessage.error('无法获取用户信息，请重新登录')
  }
  
  // 如果是编辑模式，加载请假数据
  if (isEditMode.value && leaveId.value) {
    await loadLeaveData(leaveId.value)
  }
  
  pageContentEl = document.querySelector('.page-content')
  if (pageContentEl) {
    pageContentEl.classList.add('no-scroll')
  }
})
onUnmounted(() => {
  if (pageContentEl) {
    pageContentEl.classList.remove('no-scroll')
  }
})
</script>

<style lang="scss" scoped>
.leave-form-page {
  min-height: 100vh;
  padding-top: 60px;
  padding-bottom: 120px;
  background: #ffffff;
  margin: -20px;
  padding-left: 0;
  padding-right: 0;
}

.page-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  z-index: 1000;
  
  .header-content {
    text-align: center;
    
    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
      line-height: 1.4;
    }
  }
}

.form-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.form-body {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  :deep(.el-form-item) {
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    
    .el-form-item__label {
      font-size: 14px;
      font-weight: 500;
      color: #333;
      line-height: 1.5;
      margin-bottom: 0;
      display: flex;
      align-items: center;
      min-height: 48px;
    }
    
    .el-form-item__content {
      margin-top: 0;
      flex: 1;
    }
  }
  
  :deep(.el-input__wrapper) {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 12px 16px;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #1890ff;
    }
    
    &.is-focus {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
    }
  }
  
  :deep(.el-select .el-input__wrapper) {
    cursor: pointer;
  }
  
  :deep(.el-date-editor.el-input__wrapper) {
    cursor: pointer;
  }
  
  :deep(.el-input-number .el-input__wrapper) {
    padding-right: 50px;
  }
  
  :deep(.el-textarea__inner) {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 12px 16px;
    min-height: 100px;
    resize: vertical;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #1890ff;
    }
    
    &:focus {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
    }
  }
  
  :deep(.el-input.is-disabled .el-input__wrapper) {
    background: #f5f5f5;
    color: #999;
    cursor: not-allowed;
  }
  
  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    background: #f5f5f5;
    color: #999;
    cursor: not-allowed;
  }
}

.days-display {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 4px;
  min-height: 48px;
  
  .days-value {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
  
  .days-unit {
    font-size: 14px;
    color: #666;
  }
}

.bottom-submit {
  position: fixed;
  bottom: 64px;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 12px;
  border-top: 1px solid #e8e8e8;
  z-index: 100;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  
  .submit-btn {
    height: 44px;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &.primary {
      background: linear-gradient(135deg, #00d4aa 0%, #00b8d4 100%);
      color: white;
      
      &:hover {
        background: linear-gradient(135deg, #00c19a 0%, #00a5c4 100%);
      }
      
      &:active {
        background: linear-gradient(135deg, #00b8a0 0%, #0095b4 100%);
      }
      
      &:disabled {
        background: #ccc;
        cursor: not-allowed;
      }
    }
    
    &.secondary {
      background: #f8f9fa;
      color: #333;
      border: 1px solid #e9ecef;
      
      &:hover {
        background: #e9ecef;
        border-color: #dee2e6;
      }
      
      &:active {
        background: #dee2e6;
      }
    }
  }
}

@media (max-width: 768px) {
  .leave-form-page {
    padding-top: 56px;
    padding-bottom: 112px;
    margin: -15px;
    padding-left: 0;
    padding-right: 0;
  }
  
  .page-header {
    padding: 12px 16px;
    
    .page-title {
      font-size: 16px;
    }
  }
  
  .form-container {
    padding: 16px;
  }
  
  .form-body {
    padding: 20px;
    border-radius: 8px;
  }
  
  .bottom-submit {
    bottom: 64px;
    padding: 10px;
    gap: 10px;
    
    .submit-btn {
      height: 40px;
      font-size: 14px;
    }
  }
}
</style>


